<?php

namespace addons\shopro\controller;

use addons\shopro\exception\Exception;
use addons\shopro\library\Wechat as WechatLibrary;
use addons\shopro\model\Store as ModelStore;
use addons\shopro\model\User;
use addons\shopro\model\UserStore;
use think\Db;

class Store extends Base
{

    protected $noNeedLogin = ['store_category_data','store_area_data','store_list','store_index'];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $user = User::info();
        $userStore = UserStore::where('user_id', $user->id)->select();
        $dianyuan = Db::name('shopro_user_store_dianyuan')->where('user_id',$user->id)->select();
        $userStore = array_merge($userStore,$dianyuan);
        $store_id_arr = array_column($userStore, 'store_id');

        $stores = [];
        if ($store_id_arr) {
            $stores = ModelStore::show()->where('id', 'in', $store_id_arr)->select();
        }
        
        $this->success('获取商家列表', $stores);
    }
    /*查看店员列表*/
    public function dianyuan_list(){
        $store_id = $this->request->get('store_id');
        $user_id = (int)$this->auth->id;

        $is_admin = Db::name('shopro_user_store')
            ->where('store_id',$store_id)
            ->where('user_id',$user_id)
            ->find();

        if (empty($is_admin)){$this->error('当前商家您不是管理员');}
        $list = Db::name('shopro_user_store_dianyuan')
            ->alias('a')
            ->join('user u','a.user_id = u.id')
            ->where('a.store_id',$store_id)
            ->field('a.user_id,u.nickname,u.avatar,u.mobile')
            ->select();
        if ($list){
            $this->success('获取成功',$list);
        }else{
            $this->success('获取成功',[]);
        }

    }
    /*生成添加店员二维码*/
    public function generate_qrcode(){

        $scene = 'store=1';
        $path = $this->request->get('path', '');

        if (empty($path)) {
            $path = 'pages/index/index';
        }

        $wechat = new WechatLibrary('wxMiniProgram');
        $content = $wechat->getApp()->app_code->getUnlimit($scene, [
            'page' => $path,
            'is_hyaline' => true,
        ]);

        if ($content instanceof \EasyWeChat\Kernel\Http\StreamResponse) {

            return response($content->getBody(), 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        } else {
            // 小程序码获取失败
            $msg = isset($content['errcode']) ? $content['errcode'] : '-';
            $msg .= isset($content['errmsg']) ? $content['errmsg'] : '';
            \think\Log::write('wxacode-error' . $msg);

            $this->error('获取失败', $msg);
        }
    }
    /*添加店员二维码*/
    public function generate_add(){

        $scene = 'store=1';
        $path = $this->request->get('path', '');

        if (empty($path)) {
            $path = 'pages/index/index';
        }

        $wechat = new WechatLibrary('wxMiniProgram');
        $content = $wechat->getApp()->app_code->getUnlimit($scene, [
            'page' => $path,
            'is_hyaline' => true,
        ]);

        if ($content instanceof \EasyWeChat\Kernel\Http\StreamResponse) {

            return response($content->getBody(), 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        } else {
            // 小程序码获取失败
            $msg = isset($content['errcode']) ? $content['errcode'] : '-';
            $msg .= isset($content['errmsg']) ? $content['errmsg'] : '';
            \think\Log::write('wxacode-error' . $msg);

            $this->error('获取失败', $msg);
        }
    }
    /*管理员解除店员权限*/
    public function remove_dianyuan(){
        $store_id = $this->request->get('store_id');
        if (empty($store_id)){$this->error('商家ID不存在');}
        $user_id = $this->request->get('user_id');
        $admin_id = (int)$this->auth->id;


        $userlist = explode(",", $user_id);

        foreach ($userlist as $v){
            if (empty($store_id)){$this->error('存在店员ID不存在');}
            $is_admin = Db::name('shopro_user_store')
                ->where('store_id',$store_id)
                ->where('user_id',$admin_id)
                ->find();
            if (empty($is_admin)){$this->error('存在当前商家您不是管理员，无法删除店员');}
            $is_dianyuan = Db::name('shopro_user_store_dianyuan')
                ->where('store_id',$store_id)
                ->where('user_id',$v)
                ->find();
            if (empty($is_dianyuan)){$this->error('存在用户不是当前商家店员');}
            $a = Db::name('shopro_user_store_dianyuan')
                ->where('store_id',$store_id)
                ->where('user_id',$v)
                ->delete();
//            if (!empty($a)){$this->success('删除店员成功');}else{$this->error('删除失败');}
        }
        $this->success('删除店员成功');
    }
    /*被邀请用户加入商家*/
    public function join_stroe(){
        $store_id = $this->request->get('store_id');
        if (empty($store_id)){$this->error('商家ID不存在');}
        $dianyuan_id = $this->request->get('dianyuan_id');
        if (empty($dianyuan_id)){$this->error('店员ID不存在');}
        $user_id = (int)$this->auth->id;

        $is_admin = Db::name('shopro_user_store')
            ->where('store_id',$store_id)
            ->where('user_id',$user_id)
            ->find();
        if (empty($is_admin)){$this->error('当前商家您不是管理员');}

        if ($dianyuan_id==$user_id){$this->error('自己无法成为店员');}
        $is_dianyuana = Db::name('shopro_user_store_dianyuan')
            ->where('store_id',$store_id)
            ->where('user_id',$dianyuan_id)
            ->find();
        if (!empty($is_dianyuana)){$this->error('当前用户已是店员');}
        $data = ['user_id' => $dianyuan_id, 'store_id' => $store_id];
        $a = Db::name('shopro_user_store_dianyuan')->insert($data);
        if (!empty($a)){$this->success('加入成功');}
    }
    /*获取商家分类数据*/
    public function store_category_data(){
        $data = [];
        $list = Db::name('category')->where('pid',0)->where('status','normal')->field('id,pid,name,weigh,image,status')->order('weigh desc')->select();
        if (!empty($list)){
            foreach ($list as &$v){

                $child = Db::name('category')->where('pid',$v['id'])->where('status','normal')->field('id,pid,name,image,weigh,status')->order('weigh desc')->select();


                $v['child'] = array_chunk($child, 10);
            }
            unset($v);
            $data =  $list;
        }
        $this->success('获取成功',$list);
    }
    /*获取商家区域数据*/
    public function store_area_data(){
        $city = $this->request->get('city');
        $area = cache('area-cascader');
        $this->model = new \app\admin\model\shopro\Area;
        $area = $this->model->cache(true)->with('children.children')->where('level', 1)->order('id asc')->select();
        $children = [];
        foreach ($area as $v){
            foreach ($v['children'] as $k){
                if ($k['name']==$city){
                    $children = $k['children'];
                    break;
                }
            }
        }
        $this->success('省市区列表', $children );
    }
    
    
    public function store_list(){
        $params = $this->request->post();
        //todo 最近距离，地域，好评，今日营业，价格，最新推荐
        $keyword = $params['keyword'] ?? 0;
        $latitude = $params['latitude'] ?? 0;
        $longitude = $params['longitude'] ?? 0;
        $category_id =  $params['category_id'] ?? 0;
        $province_id = $params['province_id'] ?? 0;
        $city_id = $params['city_id'] ?? 0;
        $area_id = $params['area_id'] ?? 0;
        $is_new = $params['is_new'] ?? 0;
        $is_haoping = $params['is_haoping'] ?? 0;
        $is_yingye = $params['is_yingye'] ?? 0;
        $is_jiage = $params['is_jiage'] ?? 0;
        $shelf_platform = isset($params['shelf_platform']) ? $params['shelf_platform']:'1';//商品上架平台 1：微信  2：抖音 3：微信+抖音+快手 4=快手 5:微信+抖音 6:微信+快手 7:抖音+快手


        if ($shelf_platform=='4'){
            $province_id='340000';
            $city_id='340100';
            $area_id='';
        }

        $pindex = $params['pindex'] ?? 1;
        $psize = 10;

        $selfetch =new  \addons\shopro\model\Store;
        if ($keyword) {
            $selfetch = $selfetch->where('name|hide_title','like','%'.$keyword.'%');
        }
        if ($province_id) {
            $selfetch = $selfetch->where('province_id',$province_id);
        }
        if ($city_id) {
            $selfetch = $selfetch->where('city_id',$city_id);
        }
        if ($area_id) {
            $selfetch = $selfetch->where('area_id',$area_id);
        }
        $selfetch = $selfetch->where('status',1);
        if ($category_id) {

            $category_info = Db::name('category')->where('id',$category_id)->find();

            if ($category_info['pid']==0){//传入一级分类ID

                $category_ids = Db::name('category')->where('pid',$category_id)->select();
                $ids = array_column($category_ids, 'id');

                $e = "find_in_set('$category_id',category_id)";
                foreach ($ids as $vv){
                    $e .=" OR find_in_set('$vv',category_id)";

                }
                $selfetch = $selfetch->where($e);
            }else{
                $selfetch = $selfetch->where("find_in_set('$category_id',category_id)");
            }
//            if ($category_id==19) {
//                $selfetch = $selfetch->where('selfetch', 0);
//            }


        }

        if ($is_yingye) {
            $openweeks = date("w")==0?7:date("w");

            $selfetch = $selfetch->where('openweeks','like','%'.$openweeks.'%');
        }

        if (empty($keyword) && empty($pid) && empty($is_new) && (empty($is_haoping)||empty($is_yingye)||empty($is_jiage))) {
            $selfetch = $selfetch->order('is_topping', 'desc');
        }
        
        if ($latitude && $longitude ) {
            $selfetch = $selfetch->field('*, ' . getDistanceBuildertwo($latitude, $longitude))->order('distance', 'asc');
        }
        if ($is_new) {
            $selfetch = $selfetch->order('createtime', 'desc');
        }

        $selfetch = $selfetch->select();



        if (!empty($selfetch)){

            foreach ($selfetch as &$v){


                

                $goods_list = Db::name('shopro_goods')->where('shopro_store_id',$v['id'])->field('id')->select();
                if ($goods_list){
                    foreach ($goods_list as $val) {
                        $val = join(",",$val);
                        $temp_array[] = $val;
                    }
                    $str = implode(",", $temp_array);

                    $comment_count = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->count();
                    $comment_total = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->sum('level');

                    if ($comment_count==0){
                        $v['pingfen'] = 4;
                    }else{
                        $v['pingfen'] = bcdiv($comment_total,$comment_count,0);

                    }


                    $count = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->count();
                    $total = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->sum('price');
                    if ($count==0){
                        $v['jiage'] = 0;
                    }else{
                        $v['jiage'] = bcdiv($total, $count,0);
                    }

                }else{
                    $v['pingfen'] = 4;
                    $v['jiage'] = 0;
                }
                if ($v['category_id']){
                    $v['category_name'] = Db::name('category')->where('id',$v['category_id'])->value('name');
                }

                if ($shelf_platform==='1'){
                    $ds = ['1','3','5','6'];
                }
                if ($shelf_platform==='2'){
                    $ds = ['2','3','5','7'];
                }
                if ($shelf_platform==='3'){
                    $ds = ['1'];
                }
                if ($shelf_platform=='4'){
                    $ds = ['4','3','6','7'];
                }

                $v['hold_goods'] =  Db::name('shopro_goods')
                    ->where('shopro_store_id',$v['id'])
                    ->where('shelf_platform','in',$ds)
                    ->where('status','up')
                    ->where('deletetime',null)
                    ->field('id,title,sales')
                    ->order('sales desc')
                    ->find();

                $v['new_goods'] =  Db::name('shopro_goods')
                    ->where('shopro_store_id',$v['id'])
                    ->where('shelf_platform','in',$ds)
                    ->where('status','up')
                    ->where('deletetime',null)
                    ->field('id,title')
                    ->order('createtime desc')
                    ->find();

                if (!empty($v['banner_images'])){
                    $banner_images_array = explode(',',$v['banner_images']);
                    foreach ($banner_images_array as $banner_images_key=>$banner_images_item){
                        $banner_images_array[$banner_images_key] = cdnurl($banner_images_item,true);
                    }
                    $v['banner_images'] = $banner_images_array;
                }else{

                    $v['banner_images'] = [];

                }

               
                
                $v['logo_images'] = cdnurl($v['logo_images'],true);
               
                $tmp = explode(',',$v['logo_images']);
                
                $v['logo_images'] = $tmp[0]??'';

                //$v['banner_images'] = explode(',', $v['banner_images']);

                $openweeks = explode(',', $v['openweeks']);
                $w = date("w")==0?'7':date("w");
                if (in_array($w,$openweeks)){
                    $openhours = explode(' - ', $v['openhours']);
                    $Day = date('Y-m-d ',time());
                    $timeBegin = strtotime($Day.$openhours[0].":00");
                    $timeEnd = strtotime($Day.$openhours[1].":00");
                    $curr_time = time();
                    if($curr_time >= $timeBegin && $curr_time <= $timeEnd){
                        $v['is_business'] = 1;
                    }
                }else{
                    $v['is_business'] = 0;
                }
                if (empty($v['two_category'])){
                    $v['two_category']='';
                }
            }
            unset($v);


            if ($is_haoping) {
                $selfetch = multi_array_sort($selfetch, 'pingfen',SORT_DESC);
            }

            if ($is_jiage){
                $selfetch = multi_array_sort($selfetch, 'jiage',$is_jiage=='desc'?SORT_DESC:SORT_ASC);
            }


            $start = ($pindex - 1) * $psize;

            if (!empty($selfetch)) {
                $selfetch = array_slice($selfetch, $start, $psize);
            }

        }else{
            $selfetch = [];
        }




        $this->success('获取成功', $selfetch);
    }
    
    
        public function store_list1(){
        $params = $this->request->post();
        //todo 最近距离，地域，好评，今日营业，价格，最新推荐
        $keyword = $params['keyword'] ?? 0;
        $latitude = $params['latitude'] ?? 0;
        $longitude = $params['longitude'] ?? 0;
        $category_id =  $params['category_id'] ?? 0;
        $province_id = $params['province_id'] ?? 0;
        $city_id = $params['city_id'] ?? 0;
        $area_id = $params['area_id'] ?? 0;
        $is_new = $params['is_new'] ?? 0;
        $is_haoping = $params['is_haoping'] ?? 0;
        $is_yingye = $params['is_yingye'] ?? 0;
        $is_jiage = $params['is_jiage'] ?? 0;
        $shelf_platform = isset($params['shelf_platform']) ? $params['shelf_platform']:'1';//商品上架平台 1：微信  2：抖音 3：微信+抖音+快手 4=快手 5:微信+抖音 6:微信+快手 7:抖音+快手


        if ($shelf_platform=='4'){
            $province_id='340000';
            $city_id='340100';
            $area_id='';
        }

        $pindex = $params['pindex'] ?? 1;
        $psize = 10;

        $selfetch =new  \addons\shopro\model\Store;
        if ($keyword) {
            $selfetch = $selfetch->where('name|hide_title','like','%'.$keyword.'%');
        }
        if ($province_id) {
            $selfetch = $selfetch->where('province_id',$province_id);
        }
        if ($city_id) {
            $selfetch = $selfetch->where('city_id',$city_id);
        }
        if ($area_id) {
            $selfetch = $selfetch->where('area_id',$area_id);
        }
        $selfetch = $selfetch->where('status',1);
        if ($category_id) {

            $category_info = Db::name('category')->where('id',$category_id)->find();

            if ($category_info['pid']==0){//传入一级分类ID

                $category_ids = Db::name('category')->where('pid',$category_id)->select();
                $ids = array_column($category_ids, 'id');

                $e = "find_in_set('$category_id',category_id)";
                foreach ($ids as $vv){
                    $e .=" OR find_in_set('$vv',category_id)";

                }
                $selfetch = $selfetch->where($e);
            }else{
                $selfetch = $selfetch->where("find_in_set('$category_id',category_id)");
            }
//            if ($category_id==19) {
//                $selfetch = $selfetch->where('selfetch', 0);
//            }


        }

        if ($is_yingye) {
            $openweeks = date("w")==0?7:date("w");

            $selfetch = $selfetch->where('openweeks','like','%'.$openweeks.'%');
        }

        if (empty($keyword) && empty($pid) && empty($is_new) && (empty($is_haoping)||empty($is_yingye)||empty($is_jiage))) {
            $selfetch = $selfetch->order('is_topping', 'desc');
        }
        
        if ($latitude && $longitude ) {
            $selfetch = $selfetch->field('*, ' . getDistanceBuildertwo($latitude, $longitude))->order('distance', 'asc');
        }
        if ($is_new) {
            $selfetch = $selfetch->order('createtime', 'desc');
        }

        $selfetch = $selfetch->select();



        if (!empty($selfetch)){

            foreach ($selfetch as &$v){


                

                $goods_list = Db::name('shopro_goods')->where('shopro_store_id',$v['id'])->field('id')->select();
                if ($goods_list){
                    foreach ($goods_list as $val) {
                        $val = join(",",$val);
                        $temp_array[] = $val;
                    }
                    $str = implode(",", $temp_array);

                    $comment_count = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->count();
                    $comment_total = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->sum('level');

                    if ($comment_count==0){
                        $v['pingfen'] = 4;
                    }else{
                        $v['pingfen'] = bcdiv($comment_total,$comment_count,0);

                    }


                    $count = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->count();
                    $total = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->sum('price');
                    if ($count==0){
                        $v['jiage'] = 0;
                    }else{
                        $v['jiage'] = bcdiv($total, $count,0);
                    }

                }else{
                    $v['pingfen'] = 4;
                    $v['jiage'] = 0;
                }
                if ($v['category_id']){
                    $v['category_name'] = Db::name('category')->where('id',$v['category_id'])->value('name');
                }

                if ($shelf_platform==='1'){
                    $ds = ['1','3','5','6'];
                }
                if ($shelf_platform==='2'){
                    $ds = ['2','3','5','7'];
                }
                if ($shelf_platform==='3'){
                    $ds = ['1'];
                }
                if ($shelf_platform=='4'){
                    $ds = ['4','3','6','7'];
                }

                $v['hold_goods'] =  Db::name('shopro_goods')
                    ->where('shopro_store_id',$v['id'])
                    ->where('shelf_platform','in',$ds)
                    ->where('status','up')
                    ->where('deletetime',null)
                    ->field('id,title,sales')
                    ->order('sales desc')
                    ->find();

                $v['new_goods'] =  Db::name('shopro_goods')
                    ->where('shopro_store_id',$v['id'])
                    ->where('shelf_platform','in',$ds)
                    ->where('status','up')
                    ->where('deletetime',null)
                    ->field('id,title')
                    ->order('createtime desc')
                    ->find();

                if (!empty($v['banner_images'])){
                    $banner_images_array = explode(',',$v['banner_images']);
                    foreach ($banner_images_array as $banner_images_key=>$banner_images_item){
                        $banner_images_array[$banner_images_key] = cdnurl($banner_images_item,true);
                    }
                    $v['banner_images'] = $banner_images_array;
                }else{

                    $v['banner_images'] = [];

                }

                $v['logo_images'] = cdnurl($v['logo_images'],true);

                //$v['banner_images'] = explode(',', $v['banner_images']);

                $openweeks = explode(',', $v['openweeks']);
                $w = date("w")==0?'7':date("w");
                if (in_array($w,$openweeks)){
                    $openhours = explode(' - ', $v['openhours']);
                    $Day = date('Y-m-d ',time());
                    $timeBegin = strtotime($Day.$openhours[0].":00");
                    $timeEnd = strtotime($Day.$openhours[1].":00");
                    $curr_time = time();
                    if($curr_time >= $timeBegin && $curr_time <= $timeEnd){
                        $v['is_business'] = 1;
                    }
                }else{
                    $v['is_business'] = 0;
                }
                if (empty($v['two_category'])){
                    $v['two_category']='';
                }
            }
            unset($v);


            if ($is_haoping) {
                $selfetch = multi_array_sort($selfetch, 'pingfen',SORT_DESC);
            }

            if ($is_jiage){
                $selfetch = multi_array_sort($selfetch, 'jiage',$is_jiage=='desc'?SORT_DESC:SORT_ASC);
            }


            $start = ($pindex - 1) * $psize;

            if (!empty($selfetch)) {
                $selfetch = array_slice($selfetch, $start, $psize);
            }

        }else{
            $selfetch = [];
        }




        $this->success('获取成功', $selfetch);
    }
    
    
    /*商家商品列表查看*/
    public function goods_list(){
        $userid = $this->auth->id;
        $store_id =  $this->request->get('store_id');
        if (empty($store_id)){
            $this->error('商家ID不存在');
        }
        $info = Db::name('shopro_user_store')->where('user_id',$userid)->where('store_id',$store_id)->find();
        if (empty($info)){
            $this->error('对应商家无权限');
        }

        $goods_list = Db::name('shopro_goods')
            ->where('shopro_store_id',$store_id)
            ->field('id,title,subtitle,status,weigh,image,original_price,price')
            ->select();
        foreach ($goods_list as &$v){
            $v['image'] = cdnurl($v['image']);
            $v['stock'] = Db::name('shopro_goods_sku_price')->where('goods_id',$v['id'])->sum('stock');
        }
        unset($v);
        $this->success('获取成功', $goods_list);
    }
    /*商家对商品进行上下架操作*/
    public function good_update(){
        $userid = $this->auth->id;
        $store_id =  $this->request->get('store_id');
        $type =  $this->request->get('type');
        $good_id =  $this->request->get('good_id');
        if (empty($store_id)){
            $this->error('商家ID不存在');
        }
        $info = Db::name('shopro_user_store')->where('user_id',$userid)->where('store_id',$store_id)->find();
        if (empty($info)){
            $this->error('对应商家无权限');
        }
        $goods_info =  Db::name('shopro_goods')->where('id',$good_id)->where('shopro_store_id',$store_id)->find();
        if (empty($goods_info)){
            $this->error('商品不存在');
        }

        if (!in_array($type, array('up','down'))){
            $this->error('类型不正确');
        }
        if ($type=='up'&& $goods_info['status']=='up'){
            $this->error('当前商品已是上架状态');
        }
        if ($type=='down'&& $goods_info['status']=='down'){
            $this->error('当前商品已是下架状态');
        }
        Db::name('shopro_goods')->where('id',$good_id)->where('shopro_store_id',$store_id)->update(['status' => $type]);
        $this->success('更新成功');
    }
    /*商家收藏*/
    /**
     * @return Auth
     */
    public function store_favorite()
    {
        $userid = $this->auth->id;
        $store_id =  $this->request->get('store_id');
        if (empty($store_id)){
            $this->error('商家ID不存在');
        }
        $info = Db::name('shopro_store')->where('id',$store_id)->find();
        if (empty($info)){
            $this->error('商家不存在');
        }
        $is_shouchang = Db::name('shopro_user_store_favorite')
            ->where('user_id',$userid)
            ->where('store_id',$store_id)
            ->where('deletetime',null)
            ->find();
        if (!empty($is_shouchang)){
            $this->error('已收藏');
        }
        $data = array(
            'user_id'=>$userid,
            'store_id'=>$store_id,
            'createtime'=>time(),
            'updatetime'=>time()
        );
        Db::name('shopro_user_store_favorite')->insert($data);
        $this->success('收藏成功');
    }
    public function store_index_dele_favorite(){
        $userid = $this->auth->id;
        $store_id =  $this->request->get('store_id');
        if (empty($store_id)){
            $this->error('商家ID不存在');
        }
        Db::name('shopro_user_store_favorite')
            ->where('user_id',$userid)
            ->where('store_id',$store_id)
            ->delete();
        $this->success('取消收藏成功');
    }
    /*商家取消收藏*/
    /**
     * @return Auth
     */
    public function store_dele_favorite()
    {
        $userid = $this->auth->id;
        $ids =  $this->request->get('id');
        if (empty($ids)){
            $this->error('商家ID不存在');
        }
        $ids = explode(",", $ids);

        foreach ($ids as $v){


            $is_shouchang = Db::name('shopro_user_store_favorite')
                ->where('user_id',$userid)
                ->where('id',$v)
                ->where('deletetime',null)
                ->find();
            if (empty($is_shouchang)){
                $this->error('当前未收藏');
            }
            Db::name('shopro_user_store_favorite')
                ->where('user_id',$userid)
                ->where('id',$v)
                ->delete();
        }

        $this->success('取消收藏成功');
    }
    /*商家收藏列表*/
    public function store_favorite_list(){
        $userid = $this->auth->id;
        $list = Db::name('shopro_user_store_favorite')
            ->where('user_id',$userid)
            ->where('deletetime',null)
            ->select();
        foreach ($list as &$v){
            $v['info'] =  Db::name('shopro_store')
                ->where('id',$v['store_id'])
                ->field('name,id,logo_images as images')
                ->find();
            $v['info']['images'] = cdnurl($v['info']['images']);
            $v['format_date']  = $this->format_date($v['createtime']);
        }
        unset($v);
        $this->success('获取成功',$list?:[]);
    }
    function format_date($time){
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }
    /*商家足迹取消收藏*/
    /**
     * @return Auth
     */
    public function store_dele_view()
    {
        $userid = $this->auth->id;
        $ids =  $this->request->get('id');
        if (empty($ids)){
            $this->error('ID不存在');
        }
        $ids = explode(",", $ids);

        foreach ($ids as $v){

            $info = Db::name('shopro_user_store_view')->where('id',$v)->where('user_id',$userid)->find();
            if (empty($info)){
                $this->error('记录不存在');
            }
            $is_shouchang = Db::name('shopro_user_store_view')
                ->where('user_id',$userid)
                ->where('id',$v)
                ->where('deletetime',null)
                ->find();
            if (empty($is_shouchang)){
                $this->error('当前未有足迹');
            }
            Db::name('shopro_user_store_view')
                ->where('user_id',$userid)
                ->where('id',$v)
                ->delete();
        }

        $this->success('删除足迹成功');
    }
    /*商家足迹列表*/
    public function store_view_list(){
        $userid = $this->auth->id;
        $list = Db::name('shopro_user_store_view')
            ->where('user_id',$userid)
            ->where('deletetime',null)
            ->order('id desc')
            ->select();
        foreach ($list as &$v){
            $v['info'] =  Db::name('shopro_store')
                ->where('id',$v['store_id'])
                ->field('name,id,logo_images as images')
                ->find();
            $v['info']['images'] = cdnurl($v['info']['images']);
            $v['format_date']  = $this->format_date($v['createtime']);
        }
        unset($v);
        $this->success('获取成功',$list?:[]);
    }
    /*商家详情页*/
    public function store_index(){
        $userid = $this->auth->id;
        $store_id =  $this->request->get('store_id');
        $latitude = $this->request->get('latitude') ?? 0;
        $longitude = $this->request->get('longitude') ?? 0;
        $shelf_platform = $this->request->get('shelf_platform') ?? '1';
        $shelf_platform = isset($shelf_platform) ? $shelf_platform:'1';//商品上架平台 1：微信  2：抖音 3：微信+抖音+快手 4：快手 5:微信+抖音 6:微信+快手 7:抖音+快手
        if ($shelf_platform==='1'){
            $ds = ['1','3','5','6'];
        }
        if ($shelf_platform==='2'){
            $ds = ['2','3','5','7'];
        }
        if ($shelf_platform==='3'){
            $ds = ['1'];
        }
        if ($shelf_platform=='4'){
            $ds = ['4','3','6','7'];
        }
        if (empty($store_id)){
            $this->error('商家ID不存在');
        }
        if (!empty($userid)){
            //记录商家足迹
            $data = ['user_id' =>$userid, 'store_id' => $store_id,'createtime'=>time(),'updatetime'=>time()];
            Db::name('shopro_user_store_view')->insert($data);
            //记录商家足迹
        }

        $store_info = Db::name('shopro_store')
            ->where('id',$store_id)
            ->field('id,name,content,images,phone,province_name,city_name,area_name,address,latitude,longitude,openhours,banner_images,openweeks,status')
            ->find();
        if ($store_info['status']!=1){
            $this->error('当前商家已禁用');
        }
        if ($latitude && $longitude){
            $store_info['distance'] = intval(distance($latitude,$longitude,$store_info['latitude'],$store_info['longitude'],false)).'km';
        }

        $openweeks = explode(',', $store_info['openweeks']);
        $w = date("w")==0?'7':date("w");
        if (in_array($w,$openweeks)){
            $openhours = explode(' - ', $store_info['openhours']);
            $Day = date('Y-m-d ',time());
            $timeBegin = strtotime($Day.$openhours[0].":00");
            $timeEnd = strtotime($Day.$openhours[1].":00");
            $curr_time = time();
            if($curr_time >= $timeBegin && $curr_time <= $timeEnd){
                $store_info['is_business'] = 1;
            }
        }else{
            $store_info['is_business'] = 0;
        }
        if (!empty($store_info['images'])){
            $images_array = explode(',',$store_info['images']);
            foreach ($images_array as $images_key=>$images_item){
                $images_array[$images_key] = cdnurl($images_item,true);
            }
            $store_info['images'] = $images_array;
        }else{
            $store_info['images'] = '';
        }

        $goods_list = Db::name('shopro_goods')->where('shopro_store_id',$store_info['id'])->field('id')->select();

        if ($goods_list){
            foreach ($goods_list as $val) {
                $val = join(",",$val);
                $temp_array[] = $val;
            }
            $str = implode(",", $temp_array);

            $comment_count = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->count();
            $comment_total = Db::name('shopro_goods_comment')->where('goods_id','in',$str)->sum('level');
            if (empty($comment_count)){
                $store_info['pingfen'] = 4;
            }else{
                $store_info['pingfen'] = bcdiv($comment_total,$comment_count,0);
            }


            $count = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->count();
            $total = Db::name('shopro_goods_sku_price')->where('goods_id','in',$str)->sum('price');
            if (empty($count)){
                $store_info['jiage'] = 0;
            }else{
                $store_info['jiage'] = bcdiv($total, $count,0);

            }

        }else{
            $store_info['pingfen'] = 4;
            $store_info['jiage'] = 0;
        }
        $store_info['goods'] = Db::name('shopro_goods')
            ->where('shopro_store_id',$store_info['id'])
            ->where('status','up')->where('deletetime',null)
            ->where('shelf_platform','in',$ds)
            ->field('id,title,image,price,original_price')
            ->select();



        if (!empty($store_info['banner_images'])){
            $images_array = explode(',',$store_info['banner_images']);
            foreach ($images_array as $images_key=>$images_item){
                $images_array[$images_key] = cdnurl($images_item,true);
            }
            $store_info['banner_images'] = $images_array;
        }else{
            $store_info['banner_images'] = '';
        }

        $store_info['collection'] = Db::name('shopro_user_store_favorite')->where('user_id',$userid)->where('store_id',$store_id)->find()?1:0;

            $this->success('获取成功',$store_info?:[]);
    }
}
